package com.tdam2011.grupo06.control;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.tdam2011.grupo06.gui.PresentacionContacto.ItemAdapter;
import com.tdam2011.grupo06.model.*;

public class GestorPresentacionContacto
{
	private ItemAdapter adapter;
	private Context context;
	
	public GestorPresentacionContacto(ItemAdapter a, Context c)
	{
		adapter = a;
		context = c;
	}
	
	public Contacto cargarContacto(int idContacto)
	{
		ContentResolver cr = context.getContentResolver();
		Contacto aux = new Contacto();
        Cursor cur = cr.query(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, (long)idContacto), null, null, null, null);
        if (cur.moveToNext()) 
        {
        	String nombre = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
   	        aux.setNombre(nombre);
	
   	        aux.setPhotoUri( StrUriPhoto.getInstance().getPhotoUriById(context, idContacto) );
	        aux.setDbId(idContacto);
    		
	        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
	        {
	        	Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{String.valueOf(idContacto)}, null);

	        	while (pCur.moveToNext()) 
     	        {
	        		String idTel = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
	        		String tel = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	        		String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
	        		adapter.addElemetnInfo(new Telefono(Integer.parseInt(idTel), tel, Integer.parseInt(type)));   		
     	        } 
     	        pCur.close();
 	        }
	        
	        Cursor eCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = ?",new String[]{String.valueOf(idContacto)}, null);

        	while (eCur.moveToNext()) 
 	        {
        		String idMail = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
        		String m = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
        		String type = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
        		adapter.addElemetnInfo(new Email(Integer.parseInt(idMail), m, Integer.parseInt(type)));
 	        } 
 	        eCur.close();
	    }
        cur.close();
        
        return aux;
	}
}
